import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { map } from 'rxjs/operators';

import { Repository, RepositoryService } from '../../services/repository.service';
import { FormBuilder, Validators } from '@angular/forms';
import { ToasterService } from 'app/modules/share/services/toaster.service';

@Component({
	selector: 'm-profile',
	templateUrl: './profile.component.html',
	styleUrls: ['./profile.component.scss'],
})
export class ProfileComponent implements OnInit {
	constructor(
		private route: ActivatedRoute,
		private router: Router,
		private fb: FormBuilder,
		private toaster: ToasterService,
		private service: RepositoryService,
	) {}

	repoForm = this.fb.group({
		id: [0],
		uri: ['', Validators.required],
		distribution: ['', Validators.required],
		enable_source: [false],
		component_list: [['main', 'non-free', 'contrib']],
	});
	context$ = this.repoForm.valueChanges.pipe(map(value => this.preview(value)));

	ngOnInit() {
		setTimeout(() => {
			this.route.data.subscribe(data => {
				if (data['list']) {
					this.repoForm.patchValue(data['list']);
					this.repoForm.reset(this.route.snapshot.data['list']);
				}
			});
		});
	}

	reset() {
		if (this.route.snapshot.data['list']) {
			this.repoForm.reset(this.route.snapshot.data['list']);
		}
	}

	async submit() {
		const value: Repository = this.repoForm.value;
		if (value.id) {
			await this.service.put(value);
		} else {
			await this.service.create(value);
		}
		this.toaster.success('保存成功');
		setTimeout(() => {
			this.reload();
		}, 500)
  }
	async sync() {
		await this.service.sync();
		this.toaster.success('已同步');
	}

	preview(repo: Repository) {
		if (repo.uri.length == 0 || repo.distribution.length == 0) {
			return '';
		}
		var lines: string[] = [];
		var base = repo.uri + ' ' + repo.distribution + ' ' + repo.component_list.join(' ');
		lines.push('deb ' + base);
		if (repo.enable_source) {
			lines.push('deb-src ' + base);
		}
		return lines;
	}

	reload() {
		this.router.navigated = false;
		this.router.navigate([], { queryParamsHandling: 'merge' });
	}
}
